<template>
  <div class="order-monitor">
    <h1>订单监控</h1>
    
    <el-row :gutter="20" class="dashboard-header">
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-title">总订单量</div>
          <div class="card-value">{{ dashboardData.totalOrders || 0 }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-title">今日订单</div>
          <div class="card-value">{{ dashboardData.todayOrders || 0 }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-title">配送中订单</div>
          <div class="card-value">{{ dashboardData.inProgressOrders || 0 }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card warning-card">
          <div class="card-title">异常订单</div>
          <div class="card-value">{{ dashboardData.abnormalOrders || 0 }}</div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="status-distribution">
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>订单状态分布</span>
            <el-button type="text" @click="refreshStatusDistribution">刷新</el-button>
          </div>
          <div id="status-chart" style="height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>订单实时流量</span>
            <el-radio-group v-model="flowGranularity" size="mini" @change="getOrderFlow">
              <el-radio-button label="hour">小时</el-radio-button>
              <el-radio-button label="day">天</el-radio-button>
              <el-radio-button label="week">周</el-radio-button>
            </el-radio-group>
          </div>
          <div id="flow-chart" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-card class="order-list-card">
      <div slot="header" class="order-list-header">
        <span>实时订单列表</span>
        <div>
          <el-input placeholder="搜索订单号/地址/电话" v-model="searchKeyword" style="width: 200px" clearable @clear="handleSearch">
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
          </el-input>
          <el-select v-model="statusFilter" placeholder="订单状态" clearable @change="handleSearch" style="margin-left: 10px">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </div>
      </div>
      
      <div v-loading="loading">
        <el-table :data="orders" style="width: 100%">
          <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
          <el-table-column label="商家" width="150">
            <template slot-scope="scope">
              {{ scope.row.merchantName || scope.row.merchant_name || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="用户" width="120">
            <template slot-scope="scope">
              {{ scope.row.userName || scope.row.user_name || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="address" label="配送地址"></el-table-column>
          <el-table-column prop="phone" label="联系电话" width="130"></el-table-column>
          <el-table-column label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="骑手" width="100">
            <template slot-scope="{ row }">
              {{ row.riderName || (row.riderId ? '骑手#' + row.riderId : '-') }}
            </template>
          </el-table-column>
          <el-table-column label="金额" width="100">
            <template slot-scope="{ row }">
              {{ row.payAmount ? '¥' + row.payAmount : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="下单时间" width="180">
            <template slot-scope="scope">
              {{ formatDate(scope.row.createdTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="viewOrderDetail(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.page"
            :page-sizes="[10, 20, 50]"
            :page-size="pagination.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total">
          </el-pagination>
        </div>
      </div>
    </el-card>
    
    <!-- 异常订单卡片 -->
    <el-card class="abnormal-orders-card" v-if="abnormalOrders.length > 0">
      <div slot="header" class="abnormal-orders-header">
        <span>异常订单警告</span>
        <el-button type="text" @click="getAbnormalOrders">刷新</el-button>
      </div>
      
      <el-table :data="abnormalOrders" style="width: 100%">
        <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
        <el-table-column label="商家" width="150">
          <template slot-scope="scope">
            {{ scope.row.merchantName || scope.row.merchant_name || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="骑手" width="120">
          <template slot-scope="scope">
            {{ scope.row.riderName || (scope.row.riderId ? '骑手#' + scope.row.riderId : '-') }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="配送地址"></el-table-column>
        <el-table-column label="下单时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="异常原因" width="200">
          <template slot-scope="{ }">
            <el-tag type="danger">长时间未完成配送</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="{ }">
            <el-button size="mini" type="warning">处理</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { getAllOrders, getOrderStatusDistribution, getOrderRealTimeFlow, getAbnormalOrders } from '@/api/admin';
import * as echarts from 'echarts';

export default {
  name: 'OrderMonitor',
  data() {
    return {
      loading: false,
      orders: [],
      abnormalOrders: [],
      dashboardData: {},
      pagination: {
        page: 1,
        size: 10,
        total: 0
      },
      searchKeyword: '',
      statusFilter: null,
      statusOptions: [
        { value: 0, label: '待支付' },
        { value: 1, label: '待接单' },
        { value: 2, label: '配送中' },
        { value: 3, label: '已完成' },
        { value: 4, label: '已取消' }
      ],
      flowGranularity: 'hour',
      statusChart: null,
      flowChart: null
    }
  },
  mounted() {
    this.initData();
    // 设置定时刷新
    this.timerTasks = [
      setInterval(this.refreshOrderList, 60000), // 每分钟刷新订单列表
      setInterval(this.getAbnormalOrders, 120000) // 每两分钟刷新异常订单
    ];
  },
  beforeDestroy() {
    // 清除定时任务
    if (this.timerTasks) {
      this.timerTasks.forEach(timer => clearInterval(timer));
    }
    // 销毁图表实例
    if (this.statusChart) {
      this.statusChart.dispose();
    }
    if (this.flowChart) {
      this.flowChart.dispose();
    }
  },
  methods: {
    // 初始化数据
    initData() {
      this.getOrderList();
      this.getAbnormalOrders();
      this.$nextTick(() => {
        this.initStatusChart();
        this.initFlowChart();
      });
    },
    
    // 获取订单列表
    getOrderList() {
      this.loading = true;
      
      const params = {
        page: this.pagination.page,
        size: this.pagination.size,
        keyword: this.searchKeyword || undefined,
        status: this.statusFilter
      };
      
      getAllOrders(params).then(res => {
        if (res.code === 200) {
          this.orders = res.data.records || [];
          this.pagination.total = res.data.total || 0;
          
          // 更新仪表盘数据
          this.dashboardData = {
            totalOrders: res.data.total || 0,
            todayOrders: this.orders.filter(order => {
              const today = new Date().toISOString().slice(0, 10);
              return order.createdTime && order.createdTime.startsWith(today);
            }).length,
            inProgressOrders: this.orders.filter(order => order.status === 2).length,
            abnormalOrders: this.abnormalOrders.length
          };
        } else {
          this.$message.error(res.message || '获取订单数据失败');
        }
      }).catch(err => {
        console.error('获取订单列表失败', err);
        this.$message.error('获取订单数据失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 获取异常订单
    getAbnormalOrders() {
      getAbnormalOrders({
        page: 1,
        size: 10
      }).then(res => {
        if (res.code === 200) {
          this.abnormalOrders = res.data.records || [];
          
          // 更新仪表盘数据中的异常订单数
          if (this.dashboardData) {
            this.dashboardData.abnormalOrders = this.abnormalOrders.length;
          }
        }
      }).catch(err => {
        console.error('获取异常订单失败', err);
      });
    },
    
    // 初始化状态分布图表
    initStatusChart() {
      this.statusChart = echarts.init(document.getElementById('status-chart'));
      this.refreshStatusDistribution();
    },
    
    // 刷新状态分布数据
    refreshStatusDistribution() {
      getOrderStatusDistribution().then(res => {
        if (res.code === 200) {
          const data = res.data;
          const statusNames = {
            pending: '待支付',
            waiting: '待接单',
            inProgress: '配送中',
            completed: '已完成',
            canceled: '已取消'
          };
          
          const pieData = Object.keys(data.statusCounts).map(key => ({
            name: statusNames[key],
            value: data.statusCounts[key]
          }));
          
          const option = {
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              right: 10,
              top: 'center',
              data: Object.values(statusNames)
            },
            series: [
              {
                name: '订单状态',
                type: 'pie',
                radius: ['50%', '70%'],
                avoidLabelOverlap: false,
                label: {
                  show: false,
                  position: 'center'
                },
                emphasis: {
                  label: {
                    show: true,
                    fontSize: '14',
                    fontWeight: 'bold'
                  }
                },
                labelLine: {
                  show: false
                },
                data: pieData
              }
            ]
          };
          
          this.statusChart.setOption(option);
        }
      }).catch(err => {
        console.error('获取订单状态分布失败', err);
      });
    },
    
    // 初始化流量图表
    initFlowChart() {
      this.flowChart = echarts.init(document.getElementById('flow-chart'));
      this.getOrderFlow();
    },
    
    // 获取订单流量数据
    getOrderFlow() {
      getOrderRealTimeFlow({
        granularity: this.flowGranularity
      }).then(res => {
        if (res.code === 200) {
          const data = res.data;
          let xAxisData = [];
          let seriesData = [];
          
          if (this.flowGranularity === 'hour') {
            xAxisData = data.timeLabels;
            seriesData = data.orderCounts;
          } else if (this.flowGranularity === 'day') {
            xAxisData = data.dateLabels;
            seriesData = data.orderCounts;
          } else {
            xAxisData = data.weekLabels;
            seriesData = data.orderCounts;
          }
          
          const option = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              }
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: [
              {
                type: 'category',
                data: xAxisData,
                axisTick: {
                  alignWithLabel: true
                }
              }
            ],
            yAxis: [
              {
                type: 'value'
              }
            ],
            series: [
              {
                name: '订单数量',
                type: 'bar',
                barWidth: '60%',
                data: seriesData,
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#83bff6' },
                    { offset: 0.5, color: '#188df0' },
                    { offset: 1, color: '#188df0' }
                  ])
                }
              }
            ]
          };
          
          this.flowChart.setOption(option);
        }
      }).catch(err => {
        console.error('获取订单流量数据失败', err);
      });
    },
    
    // 处理搜索
    handleSearch() {
      this.pagination.page = 1;
      this.getOrderList();
    },
    
    // 刷新订单列表
    refreshOrderList() {
      this.getOrderList();
    },
    
    // 查看订单详情
    viewOrderDetail(order) {
      // 打开订单详情对话框或跳转到详情页面
      console.log('查看订单详情', order);
      this.$message.info('订单详情功能开发中');
    },
    
    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.size = size;
      this.pagination.page = 1;
      this.getOrderList();
    },
    
    // 页码变化
    handleCurrentChange(page) {
      this.pagination.page = page;
      this.getOrderList();
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '待接单',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 获取状态标签类型
    getStatusType(status) {
      const typeMap = {
        0: 'info',
        1: 'warning',
        2: 'primary',
        3: 'success',
        4: 'danger'
      };
      return typeMap[status] || '';
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '-';
      const date = new Date(dateStr);
      return date.toLocaleString();
    }
  }
}
</script>

<style scoped>
.order-monitor {
  padding: 20px;
}

.dashboard-header {
  margin-bottom: 20px;
}

.data-card {
  height: 100px;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.warning-card .card-value {
  color: #F56C6C;
}

.status-distribution {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-list-card {
  margin-bottom: 20px;
}

.order-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.abnormal-orders-card {
  margin-bottom: 20px;
}

.abnormal-orders-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 